import {ElMessage, ElMessageBox} from 'element-plus'
import service from '@/utils/request'
// import { cache } from '@/utils/cache'

export const CrudTool = (options) => {
    const defaultOptions = {
		isPage: true,       //是否分页
		primaryKey: 'id',   //主键字段
		queryForm: {},      //查询参数
		dataList: [],       //列表数据
		page: 1,            //页码
		limit: 10,          //每页数量
		total: 0,           //记录总数
		pageSizes: [10, 20, 50, 100],   //分页
		firstSelectedRow:null,          //第一条选中记录
		dataListSelections: [],         //所有选中记录
		apiUrl:{
		  list:'',		//查询API地址
		  add:'',		//添加API地址
		  edit:'',		//修改API地址
		  delete:'',	//删除API地址
		},     
        dialogTitle:'',     //对话框标题
		titleText:['添加','修改'],//添加和修改名称
		showDialog: false, //是否显示弹窗
		dataForm:{},        //对话框提交数据
        showSearch:true,	//是否显示搜索
		dataFormRef:null,	//表单对象
		rules:{}, 			//表单校验条件

		events:{
			beforOpenDialog:null,
			beforCloseDialog:null,
			beforSubmit:null,
		}
	}

	const addEventListener = (eventName, callback)=>{
		state.events[eventName] = callback;
	}

	const mergeDefaultOptions = (options, props) => {
		for (const key in options) {
			if (!Object.getOwnPropertyDescriptor(props, key)) {
				props[key] = options[key]
			}
		}
		return props
	}

	// 覆盖默认值
	const state = mergeDefaultOptions(defaultOptions, options)

	/**
	 * 点击添加
	 * @param {*} formRef 表单对象
	 */
	const addHandle = (formRef)=>{

        state.showDialog = true
        state.dialogTitle = state.titleText[0]
        
		//reset表单
		if(formRef){
			formRef.resetFields();
		}

		if(state.dataForm[state.primaryKey]){
			state.dataForm[state.primaryKey] = 0;
		}

		if(typeof state.events.beforOpenDialog == 'function'){
			state.events.beforOpenDialog(state);
		}
    }

	/**
	 * 点击修改
	 * @param {*} data 
	 */
	const editHandle = (data)=>{
        state.showDialog = true
        state.dialogTitle = state.titleText[1]
		
		var obj = null;
		if(typeof data=='undefined'){
			if(state.dataListSelections.length<1)
				return;
			obj = state.firstSelectedRow
		}else{
			obj = data
		}
        
		for(var k in state.dataForm){
			state.dataForm[k] = obj[k];
		}
		if(typeof state.events.beforOpenDialog == 'function'){
			state.events.beforOpenDialog(state);
		}
    }

	const cancelHandle = ()=>{
        state.showDialog = false
		console.log('cancelHandle')
	}

    const pageChangeHandle = (val) => {
		state.page = val;
        query();
	}

    const handleSubmit = (formRef)=>{
		if(typeof state.events.beforSubmit == 'function'){
			state.events.beforSubmit(state);
		}
		
		formRef.validate(valid=>{
			if (state.dataForm[state.primaryKey]>0){
				if(state.apiUrl.edit){
					service.post(state.apiUrl.edit, state.dataForm).then(res=>{
						if(res.code==200){
							ElMessage.success('修改成功')
							state.showDialog  = false
							query()

						}else{
							ElMessage.error(res.msg)
							
						}
					})
				}

			}else{
				if(state.apiUrl.add){
					service.post(state.apiUrl.add, state.dataForm).then(res=>{
						if(res.code==200){
							ElMessage.success('修改成功')
							state.showDialog  = false
							query()

						}else{
							ElMessage.error(res.msg)
							
						}
					})
				}

			}
		})
    }

    const selectionChangeHandle = (selections) => {
        if(selections.length>0){
			state.firstSelectedRow = selections[0]
		}
		state.dataListSelections = selections.map((item) => state.primaryKey && item[state.primaryKey])
    }

    const query = () => {console.log(state);
        if (!state.apiUrl.list) {
			return
		}
		state.dataListSelections = []
		state.firstSelectedRow = null
		service.get(state.apiUrl.list, {
            params:{
                page:  state.isPage ? state.page : null,
                limit: state.isPage ? state.limit : null,
				filter: JSON.stringify(state.queryForm)
            }
        })
        .then( res => {
            state.dataList = state.isPage = res.rows
            state.total = state ? res.total : 0
        })
    }

    const getDataList = () => {
		state.page = 1
        query();
    }

    const handleDelete = (row) => {
		if (!state.apiUrl.delete) {
			return
		}
		ElMessageBox.confirm('确定进行删除操作?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				service.post(state.apiUrl.delete, [row[state.primaryKey]]).then(() => {
					ElMessage.success('删除成功')
					query()
				})
			})
			.catch(() => {})
    }

    const handleDeleteBatch = (key) => {
		if (!state.apiUrl.delete) {
			return
		}else if(state.dataListSelections.length<1){
			return;
		}
		ElMessageBox.confirm('确定要删除选中的'+state.dataListSelections.length+'条记录么?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				service.post(state.apiUrl.delete, state.dataListSelections).then(() => {
					ElMessage.success('删除成功')
					query()
				})
			})
			.catch(() => {})
    }



	return {
		getDataList, //查询

		pageChangeHandle, // 页数或者分页数变化
		selectionChangeHandle, //选择复选框

		addHandle, //点击添加
		editHandle,//点击修改
        cancelHandle,//点击取消

		handleSubmit,//提交添加或修改
		handleDelete,//删除单个
		handleDeleteBatch,//批量删除

		addEventListener,//注册事件
	}
}
